const WxPay = require('wechatpay-node-v3'); // 支持使用require
const fs = require('fs')
const path = require('path')

const publicKeyPath = path.join(__dirname, './lib/cert/apiclient_cert.pem')
const privateKeyPath = path.join(__dirname, './lib/cert/apiclient_key.pem')

const payParams = async ({
	appid,
	mchid,
	openid,
	total,
	description,
	out_trade_no,
	notify_url,
}) => {
	//配置支付的sdk
	const pay = new WxPay({
		appid,
		mchid,
		total,
		description,
		out_trade_no,
		notify_url,
		publicKey: fs.readFileSync(publicKeyPath), // 公钥
		privateKey: fs.readFileSync(privateKeyPath), // 秘钥
	});
	console.log(total, 'total')
	try {

		const params = {
			appid,
			mchid,
			description,
			out_trade_no,
			notify_url,
			amount: {
				total,
			},
			payer: {
				openid
			},
			scene_info: {
				payer_client_ip: '127.0.0.1',
			},
		}

		let res = await pay.transactions_jsapi(params)

		return res;

	} catch (e) {
		console.log(e);
		//TODO handle the exception
	}
	// await 
}

exports.main = async (event, context) => {
	//event为客户端上传的参数
	console.log('event : ', event)

	let params = await payParams({
		...event
	})
	//返回数据给客户端
	return params
};